#ifndef MQTTCLIENT_H
#define MQTTCLIENT_H

#include <QObject>
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttSubscription>
#include <QScopedPointer>
#include <QTimer>
#include <QByteArray>
#include <QString>
#include <thread>
#include <memory>
#include "stream/images/imageReceiver.h"
#include <mutex>
class CMqttClient : public QObject
{
    Q_OBJECT
public:
    //设置单例模式
    static  std::shared_ptr<CMqttClient> GetInstance();
    ~CMqttClient();
    void init();
    void Connect(const QString &broker, int port, const QString &username, const QString &password);
    void Subscribe(const QString &topic);
    void Unsubscribe(const QString &topic);
    void Publish(const QString &topic, const QByteArray &message);
    void reconnectAndResubscribe();
    void Start();
    void SendImageData(const QByteArray &message);
    void SendTakeOverMsg(const QString &topic, const int64_t &tokenOverLevel);

signals:
    void SendBasicDatas(const QString &msg);
    void SendTakeOverInfo(const QString &msg);
private slots:
    void onConnected();
    void onDisconnected();
    void onMessageReceived(const QMqttTopicName &topic, const QByteArray &message);

private:
    explicit CMqttClient(QObject *parent = nullptr);
    void setupClient();
    void processMsg(const QString &topic, const QByteArray &message);
private:
    QMqttClient *m_MqttClient; //mqtt句柄
    QString m_broker;
    QString m_userName;
    QString m_password;
    int m_port;
    QVector<QString> subscribedTopics; // 存储所有已订阅的主题

    std::string m_PubTopic1;  //发布topic
    std::string m_SubTopic1;  //订阅topic
    std::string m_takeOverTopic; //接管订阅
    std::string m_ImagesDataTopic; //订阅对应导盲犬图片数据
    std::string m_robotSn;   //机器人的设备
    std::string m_robotIp; // 机器人IP
    std::thread m_mqttThread; //发送数据的线程
    std::shared_ptr<CImageReceiver> m_pReciever; //接收数据
    QTimer *m_keepAliveTimer;
    //QStringList subscribedTopics;
    static std::shared_ptr <CMqttClient> m_InStance;
    static std::once_flag m_flag;
};

#endif // MQTTCLIENT_H
